from PIL import Image, ImageDraw, ImageFont
from datetime import datetime
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
import os
import time
from django.shortcuts import render
from django.db import connection
import requests
import json
from django.shortcuts import render
from django.db import connection
import requests
import json
def index(request):
    api_request = requests.get("http://www.baidu.com")
    resp = {
        'title':'    title 标题  >>>  ',
        "key": api_request.content
    }
    return render(request, 'add/inde.html', context=resp)


def add_new_png_img_file(png_file_path):
    image = Image.new('RGB', (200, 200), 'black')      # 创建一个白色背景的图片
    draw = ImageDraw.Draw(image)      # 在图片上绘制数字3
    font = ImageFont.truetype('arial.ttf', 30)  # 使用合适的字体和字号
    text = 'NULL'
    current_date = datetime.now().strftime('%Y-%m-%d')
    print(current_date)
    text = current_date
    text_width, text_height = draw.textsize(text, font=font)
    x = (200 - text_width) // 2  # 计算数字在图片中的水平位置
    y = (200 - text_height) // 2  # 计算数字在图片中的垂直位置
    draw.text((x, y), text, font=font, fill='yellow')  # 填充颜色
    # 保存图片
    image.save(png_file_path)
    

def add_file(file_path , strrrr):
    f = open(file_path, "w", encoding="UTF-8")
    f.write( strrrr )
    f.close()
    return False


@csrf_exempt
def new_html_file(request):
    if request.method == 'POST':
        data={}
        print("哈哈哈哈\n哈哈哈哈\n哈哈哈哈")
        print(request.body)       # b'user-name=1&user-email=1%40q.com'
        
        describe_string = request.POST.get('html_file_describe')
        html_string = request.POST.get('html_file_content')
        
        time_stamp = str(round(time.time() * 1000))   # 1700477634782
        print(time_stamp)    # 时间戳  
        print(describe_string)  # 内容
        print(html_string)      # 内容

        html_file_path = os.path.abspath(__file__).split("add.py")[0] + "templates\html_demo\\" + time_stamp + ".html" 
        describe_txt_path = os.path.abspath(__file__).split("add.py")[0] + "templates\html_demo\\" + time_stamp + ".txt" 
        png_img_path = os.path.abspath(__file__).split("add.py")[0] + "static\img\\" + time_stamp + ".png"
        print(describe_txt_path)
        print(html_file_path)
        print(png_img_path) 
        
        add_file(describe_txt_path , describe_string)
        add_file(html_file_path , html_string)
        add_new_png_img_file(png_img_path)
        data["return_text"]='new_file_success'

    data = json.dumps(data)
    return HttpResponse(data, content_type="application/json")

